package cn.bandeqing.workerWallet.service.impl;

import cn.bandeqing.frame.exception.CodeException;
import cn.bandeqing.workerWalletRecord.entity.WorkerWalletRecord;
import cn.bandeqing.workerWalletRecord.entity.WwrType;
import cn.bandeqing.workerWalletRecord.service.IWorkerWalletRecordService;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import cn.bandeqing.workerWallet.entity.WorkerWallet;
import cn.bandeqing.workerWallet.mapper.WorkerWalletMapper;
import cn.bandeqing.workerWallet.service.IWorkerWalletService;
import jakarta.annotation.Resource;
import org.dromara.hutool.core.lang.Assert;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 工作人员钱包 服务层实现。
 *
 * @author fugui
 * @since 2024-01-15
 */
@Service
public class WorkerWalletServiceImpl extends ServiceImpl<WorkerWalletMapper, WorkerWallet> implements IWorkerWalletService {

    @Resource
    private IWorkerWalletRecordService workerWalletRecordService;

    @Override
    @Transactional
    public void changeBalance(Long workerId, String nickname, Double money, String desc, Long ocId, Long orderId, WwrType wwrType) {
        WorkerWallet ww = getById(workerId);
        Double before = ww.getWorkerBalance();
        Double after = before + money;

        boolean b = updateById(WorkerWallet.builder()
                .workerId(workerId)
                .workerBalance(after)
                .build());
        Assert.isTrue(b, () -> new CodeException("钱包变动失败"));

        boolean save = workerWalletRecordService.save(WorkerWalletRecord.builder()
                .workerId(workerId)
                .workerNickName(nickname)
                .orderId(orderId)
                .wwrType(wwrType)
                .wwrDesc(desc)
                .beforeMoney(before)
                .changeMoney(money)
                .afterMoney(after)
                .ocId(ocId)
                .build());
        Assert.isTrue(save, () -> new CodeException("钱包记录保存失败"));
    }

}
